/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.DataSource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Array;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author ngoc
 */
public class ReadingDAO implements DAOImpl<Reading>{
    
    public int getMaxId()
    {
        int num = 0;
        DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        List<Reading> readingList = new ArrayList<Reading>();
        try {
            
            String query = "select max(Idread)as IdMax from Reading ";
            stm = conn.createStatement();
            rs = stm.executeQuery(query);
            while(rs.next())
            {
                num = num+rs.getInt("IdMax");
            }
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return num;
    }
    
    @Override
    public List<Reading> getAll()
    {
        DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        List<Reading> readingList = new ArrayList<Reading>();
        try {
            
            String query = "select IdRead,NameRead,urlRead, UrlQuestion, UrlAnswer,TimeAnswer from Reading";
            stm = conn.createStatement();
            rs = stm.executeQuery(query);
            while(rs.next())
            {
                Reading reading = new Reading();
                reading.setIDRead(rs.getInt("IdRead"));
                reading.setNameRead(rs.getString("NameRead"));
                reading.setUrlRead(rs.getString("urlRead"));
                reading.setUrlQuestion(rs.getString("UrlQuestion"));
                reading.setUrlAnswer(rs.getString("UrlAnswer"));
                reading.setTimeAnswer(rs.getString("TimeAnswer"));
                readingList.add(reading);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return readingList;
    };
       @Override
   public void add (Reading reading)
   {
       DataSource s = new DataSource();
        Connection conn = s.getconnectToMSSQL();
        Statement stm  = null;
        ResultSet rs = null;
        int id = reading.getIDRead();
        try {
            
            String query = "insert into Reading(IdRead,NameRead,UrlRead,UrlQuestion,UrlAnswer,TimeAnswer) values ("+id+",'"+ reading.getNameRead()+"','"+reading.getUrlRead()+"','"+reading.getUrlQuestion()+"','"+reading.getUrlAnswer()+"','"+reading.getTimeAnswer()+"')";            
            stm = conn.createStatement();
            stm.execute(query);
        } catch (SQLException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
   };
    @Override
   public Reading getReading (int IDReading)
   {
        return null;
       
   };
       @Override
   public void update (Reading reading)
   {    
        
   };
       @Override
   public void delete (Reading reading)
   {
       
   };
   public String readFile(String url)
   {
       String file = "";
       FileInputStream f = null;
        try {
            File fi = new File("DeTai\\FileRead\\"+url);
            String a = fi.getAbsolutePath();
            f = new FileInputStream(a);
        } catch (FileNotFoundException exc) {
            System.out.println("File Not Found");
            
            //return;
        } catch (ArrayIndexOutOfBoundsException exc) {
            System.out.println("Usage: ShowFile File");
            //return;
        }
        // Đọc cho tới cuối file
        int i = 0;
        do {
           try {
               i = f.read();
           } catch (IOException ex) {
               Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
           }
            if (i != -1) {
                file += (char) i;
            }
        } while (i != -1);
        try {
            f.close();
        } catch (IOException ex) {
            Logger.getLogger(ReadingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
       return file;
   }
    public String[] readUsingBufferedReader(String fileName, Charset cs)
        throws IOException {
        File fi = new File("DeTai\\FileRead\\"+fileName);
        String a = fi.getAbsolutePath();
        File file = new File(a);
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, cs);
        BufferedReader br = new BufferedReader(isr);
        String line;
        int coutline = countLines(fileName)+1;
        
        String[] afile1 = new String[coutline];
        String[] afile2 = new String[coutline];
        int iDongThu = -1;
        while ((line = br.readLine()) != null) {
           // process the line
           iDongThu++;
           afile1[iDongThu] = line;
           //System.out.println(afile1[iDongThu]);
        }
        br.close();
        return afile1;
    }
    public int countLines(String filename) throws IOException {
    File fi = new File("DeTai\\FileRead\\"+filename);
    String a = fi.getAbsolutePath();
    InputStream is = new BufferedInputStream(new FileInputStream(a));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            //System.out.println("tong so dong: "+count);
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
    } 
    public void infoBox(String infoMessage, String titleBar)
    {
        JOptionPane.showMessageDialog(null, infoMessage,titleBar, JOptionPane.INFORMATION_MESSAGE);
    }    
    
     public void CoppyFile(String filein, String fileout){
        FileInputStream fin;
        FileOutputStream fout;
        String urlout = "DeTai\\FileRead\\"+fileout;
        try {// open input file
            try {
                fin = new FileInputStream(filein);
            } catch (FileNotFoundException exc) {
                System.out.println("Input File Not Found");
                return;
            }
 // open output file
            try {
                fout = new FileOutputStream(urlout);
            } catch (FileNotFoundException exc) {


                System.out.println("Error Opening OutputFile ");
                return;
            }
        } catch (ArrayIndexOutOfBoundsException exc) {
            System.out.println("Usage: CopyFile From To");
            return;
        }
    // Copy File
        int i;
        try {
            do {
                i = fin.read();
                if (i != -1) {
                    fout.write(i);
                }
            } while (i != -1);
        } catch (IOException exc) {
            System.out.println("File Error");
        }
        ///close fin and fout
        try {
            fin.close();
            fout.close();
        } catch (IOException ex) {
            Logger.getLogger(SpeakingDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
}
